package com.seafood.controller;

import com.seafood.common.Result;
import com.seafood.dto.ShoppingCartDTO;
import com.seafood.service.AdminUserService;
import com.seafood.service.ShoppingCartService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 购物车控制器
 */
@Tag(name = "购物车管理", description = "购物车相关API")
@RestController
@RequestMapping("/cart")
@RequiredArgsConstructor
@Validated
public class ShoppingCartController {
    
    private final ShoppingCartService shoppingCartService;
    private final AdminUserService userService;
    /**
     * 添加商品到购物车
     */
    @Operation(summary = "添加到购物车", description = "添加商品到购物车")
    @PostMapping("/add")
    public Result<ShoppingCartDTO> addToCart(@RequestParam Long productId,
                                            @RequestParam(defaultValue = "1") Integer quantity,
                                            Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            ShoppingCartDTO cartItem = shoppingCartService.addToCart(userId, productId, quantity);
            return Result.success("商品已添加到购物车", cartItem);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新购物车商品数量
     */
    @Operation(summary = "更新购物车数量", description = "更新购物车中商品的数量")
    @PutMapping("/update")
    public Result<ShoppingCartDTO> updateCartItem(@RequestParam Long productId,
                                                 @RequestParam Integer quantity,
                                                 Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            ShoppingCartDTO cartItem = shoppingCartService.updateCartItem(userId, productId, quantity);
            return Result.success("购物车更新成功", cartItem);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 从购物车移除商品
     */
    @Operation(summary = "移除购物车商品", description = "从购物车中移除指定商品")
    @DeleteMapping("/remove")
    public Result<String> removeFromCart(@RequestParam Long productId,
                                        Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            shoppingCartService.removeFromCart(userId, productId);
            return Result.success("商品已从购物车移除");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取用户购物车
     */
    @Operation(summary = "获取购物车", description = "获取当前用户的购物车")
    @GetMapping
    public Result<List<ShoppingCartDTO>> getCart(Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            List<ShoppingCartDTO> cartItems = shoppingCartService.getCartByUser(userId);
            return Result.success(cartItems);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 清空购物车
     */
    @Operation(summary = "清空购物车", description = "清空当前用户的购物车")
    @DeleteMapping("/clear")
    public Result<String> clearCart(Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            shoppingCartService.clearCart(userId);
            return Result.success("购物车已清空");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取购物车总价
     */
    @Operation(summary = "获取购物车总价", description = "计算当前用户购物车的总价")
    @GetMapping("/total")
    public Result<BigDecimal> getCartTotal(Authentication authentication) {
        try {
            Long userId = getUserIdFromAuth(authentication);
            BigDecimal total = shoppingCartService.calculateCartTotal(userId);
            return Result.success(total);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 从认证信息中获取用户ID
     */
    private Long getUserIdFromAuth(Authentication authentication) {
        // 假设用户名就是用户ID，实际项目中可能需要查询用户表
        try {
            String name = authentication.getName();
            Long userIdByName = userService.getUserIdByName(name);
            return userIdByName;
        } catch (NumberFormatException e) {
            throw new RuntimeException("无效的用户认证信息");
        }
    }
}